<template>
  <div>
    <el-container>
      <el-header height="auto" style="background: #f5f7fa; padding: 20px; border-radius: 4px; margin-bottom: 20px;">
        <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
          <!-- 时间范围选择器 -->
          <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-weight: bold; color: #606266;">时间范围：</span>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 300px;"
              @change="handleDateRangeChange"
            />
          </div>

          <!-- 状态过滤器 -->
          <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-weight: bold; color: #606266;">订单状态：</span>
            <el-select
              v-model="selectedStatus"
              placeholder="请选择状态"
              style="width: 150px;"
              @change="handleStatusChange"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <!-- 用户选择器 - 仅销售经理可见 -->
          <div v-if="this.$store.getters.roles.indexOf('sales_manager') !== -1" style="display: flex; align-items: center; gap: 10px;">
            <span style="font-weight: bold; color: #606266;">负责人：</span>
            <el-select
              v-model="selectedUser"
              placeholder="请选择用户"
              clearable
              filterable
              style="width: 200px;"
              :loading="backendloading"
              @change="handleUserChange"
            >
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.name"
                :value="user.id"
              />
            </el-select>
            <span v-if="userList.length === 0" style="color: #909399; font-size: 12px;">暂无用户数据</span>
          </div>

          <!-- 搜索按钮 -->
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-button
              type="primary"
              icon="el-icon-search"
              :loading="backendloading"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </div>
        </div>
      </el-header>

      <el-main style="padding: 0;">
        <!-- 统计数据面板 -->
        <div class="stats-dashboard">
          <!-- 订单统计 -->
          <div v-if="orderStats.length > 0" class="stats-section">
            <h4 class="section-title">订单统计</h4>
            <div class="stats-grid">
              <div
                v-for="(item, index) in orderStats"
                :key="'order-' + index"
                class="stat-card"
                :style="{ borderLeft: '4px solid ' + item.color }"
                @click="handleGetJumpOrders(item.id)"
              >
                <div class="stat-content">
                  <div class="stat-title">{{ item.name }}</div>
                  <div class="stat-number" :style="{ color: item.color }">{{ item.count }}</div>
                  <div class="stat-unit">单</div>
                </div>
                <div class="stat-icon">
                  <i class="el-icon-document" :style="{ color: item.color }" />
                </div>
              </div>
            </div>
          </div>

          <!-- 客户和WhatsApp统计 -->
          <div v-if="summaryCustomers.length > 0 || summaryWhatsappChats.length > 0" class="compact-stats">
            <div class="compact-stats-row">
              <!-- 客户统计 -->
              <div
                v-for="(item, index) in summaryCustomers"
                :key="'customer-' + index"
                class="compact-stat-item"
                @click="handleViewCustomers(item.type)"
              >
                <span class="compact-label">{{ item.name }}</span>
                <i class="el-icon-user" :style="{ color: item.color }" />
                <span class="compact-number" :style="{ color: item.color }">{{ item.count }}</span>
              </div>

              <!-- WhatsApp统计 -->
              <div
                v-for="(item, index) in summaryWhatsappChats"
                :key="'whatsapp-' + index"
                class="compact-stat-item"
                @click="handleViewWhatsappChats(item.type)"
              >
                <span class="compact-label">{{ item.name }}</span>
                <i class="el-icon-chat-line-round" :style="{ color: item.color }" />
                <span class="compact-number" :style="{ color: item.color }">{{ item.count }}</span>
              </div>
            </div>
          </div>

          <!-- 转化漏斗 -->
          <div v-if="conversionFunnel.length > 0" class="funnel-section">
            <h4 class="section-title">转化漏斗</h4>
            <div class="funnel-chart-container">
              <div id="funnelChart" ref="funnelChart" style="width: 100%; height: 600px;" />
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import { Crmordersummary } from '@/api/crm/crmorder'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import qs from 'qs'
import * as echarts from 'echarts'

export default {
  components: {
    CountTo
  },
  data() {
    return {
      backendloading: false,
      orderStats: [],
      summaryCustomers: [],
      summaryWhatsappChats: [],
      summaryStats: [],
      conversionFunnel: [],
      funnelChart: null, // ECharts实例
      dateRange: null,
      selectedStatus: 'all',
      selectedUser: null,
      userList: [],
      statusOptions: [
        {
          value: 'all',
          label: '全部状态'
        },
        {
          value: 'main',
          label: '主要状态'
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '本月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setDate(1)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '上个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            start.setDate(1)
            start.setHours(0, 0, 0, 0)
            end.setDate(0)
            end.setHours(23, 59, 59, 999)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '前三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '近半年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            start.setHours(0, 0, 0, 0)
            end.setHours(23, 59, 59, 999)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  mounted() {
    // 检查用户角色
    console.log('当前用户角色:', this.$store.getters.roles)

    // 默认选择本月
    this.setDateRange('thisMonth')

    // 获取用户列表（仅销售经理）
    this.getUserList()
  },
  beforeDestroy() {
    // 清理ECharts实例
    if (this.funnelChart) {
      this.funnelChart.dispose()
      this.funnelChart = null
    }
    // 移除resize监听器
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleGetOrderState() {
      this.backendloading = true
      const params = {}

      // 添加时间参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
      }

      // 添加状态参数
      if (this.selectedStatus !== 'all') {
        params.status = this.selectedStatus
      }

      // 添加用户参数
      if (this.selectedUser) {
        params.userId = this.selectedUser
      }

      console.log('搜索参数:', params)
      console.log('选中的用户ID:', this.selectedUser)

      Crmordersummary(params).then(response => {
        console.log('接口返回完整数据:', response)

        // 处理新的数据结构
        this.orderStats = response.order_stats || []
        this.summaryCustomers = response.summary_customers || []
        this.summaryWhatsappChats = response.summary_whatsapp_chats || []
        this.summaryStats = response.summary_stats || []

        // 计算转化漏斗数据
        this.calculateConversionFunnel()

        console.log('订单统计数据:', this.orderStats)
        console.log('客户统计数据:', this.summaryCustomers)
        console.log('WhatsApp统计数据:', this.summaryWhatsappChats)
        console.log('转化漏斗数据:', this.conversionFunnel)

        this.backendloading = false
      }).catch(err => {
        console.log(err)
        this.backendloading = false
      })
    },
    handleGetJumpOrders(id) {
      // 跳转到state=id的订单
      const query = {
        state: id
      }

      // 传递时间参数
      if (this.dateRange && this.dateRange.length === 2) {
        query.startDate = this.dateRange[0]
        query.endDate = this.dateRange[1]
      }

      // 传递状态参数
      if (this.selectedStatus !== 'all') {
        query.status = this.selectedStatus
      }

      // 传递用户参数
      if (this.selectedUser) {
        query.userId = this.selectedUser
      }

      this.$router.push({
        path: '/crm/crmorder',
        query: query
      })
    },
    handleDateRangeChange() {
      // 自动添加时分秒
      if (this.dateRange && this.dateRange.length === 2) {
        // 开始时间设置为 00:00:00
        if (!this.dateRange[0].includes(' ')) {
          this.dateRange[0] = this.dateRange[0] + ' 00:00:00'
        }
        // 结束时间设置为 23:59:59
        if (!this.dateRange[1].includes(' ')) {
          this.dateRange[1] = this.dateRange[1] + ' 23:59:59'
        }
      }
      // 时间范围变更时不自动搜索，需要点击搜索按钮
    },
    handleStatusChange() {
      // 状态变更时不自动搜索，需要点击搜索按钮
    },
    handleUserChange() {
      // 用户变更时不自动搜索，需要点击搜索按钮
    },
    handleSearch() {
      this.handleGetOrderState()
    },
    handleReset() {
      // 重置所有筛选条件
      this.selectedStatus = 'all'
      this.selectedUser = null
      this.setDateRange('thisMonth')
    },
    handleViewCustomers(type) {
      // 跳转到客户页面
      const query = {}

      // 传递时间参数
      if (this.dateRange && this.dateRange.length === 2) {
        query.startDate = this.dateRange[0]
        query.endDate = this.dateRange[1]
      }

      // 传递状态参数
      if (this.selectedStatus !== 'all') {
        query.status = this.selectedStatus
      }

      // 传递用户参数
      if (this.selectedUser) {
        query.userId = this.selectedUser
      }

      this.$router.push({
        path: '/crm/crmcustomer',
        query: query
      })
    },
    handleViewWhatsappChats(type) {
      // 跳转到WhatsApp对话页面
      const query = {}

      // 传递时间参数
      if (this.dateRange && this.dateRange.length === 2) {
        query.startDate = this.dateRange[0]
        query.endDate = this.dateRange[1]
      }

      // 传递状态参数
      if (this.selectedStatus !== 'all') {
        query.status = this.selectedStatus
      }

      // 传递用户参数
      if (this.selectedUser) {
        query.userId = this.selectedUser
      }

      this.$router.push({
        path: '/crm/crmwhatsapp',
        query: query
      })
    },
    getUserList() {
      // 仅销售经理可以获取用户列表
      if (this.$store.getters.roles.indexOf('sales_manager') !== -1) {
        console.log('开始获取用户列表...')

        // 根据API规范使用qs.stringify序列化参数
        GetUsers(qs.stringify({
          pagesize: 100,
          page: 1,
          order_by: '',
          order_desc: ''
        })).then(response => {
          console.log('接口返回的完整数据:', response)

          // 根据其他组件的用法，数据应该在 response.data.data 中
          let users = []
          if (response.data && response.data.data) {
            users = response.data.data
          } else if (response.data) {
            users = response.data
          } else if (Array.isArray(response)) {
            users = response
          }

          // 确保数据格式正确
          this.userList = users.map(user => {
            return {
              id: user.id || user.userId || user.user_id,
              name: user.first_name + user.last_name || user.username || `用户${user.id}`
            }
          })

          console.log('处理后的用户列表:', this.userList)
        }).catch(err => {
          console.error('获取用户列表失败:', err)
          this.$message.error('获取用户列表失败')
        })
      }
    },
    setDateRange(type) {
      const today = new Date()
      let start, end

      switch (type) {
        case 'thisMonth':
          start = new Date(today.getFullYear(), today.getMonth(), 1)
          start.setHours(0, 0, 0, 0)
          end = new Date()
          end.setHours(23, 59, 59, 999)
          break
        case 'lastMonth':
          start = new Date(today.getFullYear(), today.getMonth() - 1, 1)
          start.setHours(0, 0, 0, 0)
          end = new Date(today.getFullYear(), today.getMonth(), 0)
          end.setHours(23, 59, 59, 999)
          break
        case 'last3Months':
          start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          start.setHours(0, 0, 0, 0)
          end = new Date()
          end.setHours(23, 59, 59, 999)
          break
        case 'last6Months':
          start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
          start.setHours(0, 0, 0, 0)
          end = new Date()
          end.setHours(23, 59, 59, 999)
          break
        default:
          return
      }

      this.dateRange = [
        this.formatDate(start),
        this.formatDate(end)
      ]
      this.handleGetOrderState()
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    calculateConversionFunnel() {
      // 基于订单统计数据计算转化漏斗
      if (this.orderStats.length === 0) {
        this.conversionFunnel = []
        this.renderFunnelChart([])
        return
      }

      // 获取客户总数作为漏斗起点
      let totalCustomers = 0
      if (this.summaryCustomers.length > 0) {
        const totalCustomerItem = this.summaryCustomers.find(item => item.name.includes('总'))
        totalCustomers = totalCustomerItem ? totalCustomerItem.count
          : this.summaryCustomers.reduce((sum, item) => sum + item.count, 0)
      }

      // 如果没有客户数据，使用订单总数
      if (totalCustomers === 0) {
        totalCustomers = this.orderStats.reduce((sum, item) => sum + item.count, 0)
      }

      // 直接使用数组原本的顺序，不进行排序
      const sortedOrderStats = this.orderStats

      console.log('订单状态数据:', sortedOrderStats)

      // 准备ECharts漏斗图数据
      const funnelData = []

      // 添加起始步骤
      funnelData.push({
        name: '新客户',
        value: totalCustomers,
        itemStyle: {
          color: '#FF6B6B'
        }
      })

      // 根据排序后的订单状态创建漏斗步骤
      sortedOrderStats.forEach((stat, index) => {
        const colors = ['#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8']

        // 计算当前步骤的漏斗数值：当前状态数量 + 后续所有状态数量
        let currentStepValue = 0
        for (let i = index; i < sortedOrderStats.length; i++) {
          currentStepValue += sortedOrderStats[i].count
        }

        // 计算前一步的数量用于转化率计算
        let previousStepValue
        if (index === 0) {
          // 第一个状态的前一步是新客户总数
          previousStepValue = totalCustomers
        } else {
          // 后续状态的前一步是前一个漏斗步骤的数值
          const previousStepIndex = index - 1
          previousStepValue = 0
          for (let i = previousStepIndex; i < sortedOrderStats.length; i++) {
            previousStepValue += sortedOrderStats[i].count
          }
        }

        const conversionRate = previousStepValue > 0 ? ((currentStepValue / previousStepValue) * 100).toFixed(1) : 0

        funnelData.push({
          name: stat.name,
          value: currentStepValue, // 使用累计数值而不是单独的count
          itemStyle: {
            color: colors[index % colors.length]
          },
          // 保存原始数据用于点击事件
          originalData: {
            id: stat.id,
            conversionRate: conversionRate,
            originalCount: stat.count // 保存原始数量用于点击跳转
          }
        })
      })

      this.conversionFunnel = funnelData
      this.renderFunnelChart(funnelData)
    },
    renderFunnelChart(data) {
      this.$nextTick(() => {
        if (!this.$refs.funnelChart) return

        // 销毁已存在的图表实例
        if (this.funnelChart) {
          this.funnelChart.dispose()
        }

        // 创建新的图表实例
        this.funnelChart = echarts.init(this.$refs.funnelChart)

        const option = {
          title: {
            text: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              const data = params.data
              const conversionRate = data.originalData ? data.originalData.conversionRate : ''
              let tooltipText = `<strong>${params.name}</strong><br/>`
              tooltipText += `数量: <span style="color: #67C23A">${params.value}人</span>`
              if (conversionRate && conversionRate !== '100') {
                tooltipText += `<br/>转化率: <span style="color: #FFE135">${conversionRate}%</span>`
              }
              return tooltipText
            }
          },
          series: [
            {
              name: '转化漏斗',
              type: 'funnel',
              left: '10%',
              top: 60,
              bottom: 60,
              width: '80%',
              min: 0,
              max: Math.max(...data.map(item => item.value)),
              minSize: '0%',
              maxSize: '100%',
              sort: 'none',
              gap: 2,
              label: {
                show: true,
                position: 'inside',
                formatter: function(params) {
                  const data = params.data
                  const conversionRate = data.originalData ? data.originalData.conversionRate : ''
                  const originalCount = data.originalData ? data.originalData.originalCount : params.value

                  let labelText = `${params.name}\n`

                  // 如果是第一步"新客户"，只显示总数
                  if (params.name === '新客户') {
                    labelText += `${params.value}`
                  } else {
                    // 其他步骤显示"当前:x总:x"
                    labelText += `当前:${originalCount}总:${params.value}`
                  }

                  if (conversionRate && conversionRate !== '100') {
                    labelText += `\n转化率: ${conversionRate}%`
                  }

                  return labelText
                },
                fontSize: 14,
                fontWeight: 'bold',
                color: '#fff',
                textShadowColor: 'rgba(0, 0, 0, 0.6)',
                textShadowBlur: 2
              },
              labelLine: {
                length: 10,
                lineStyle: {
                  width: 1,
                  type: 'solid'
                }
              },
              itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
              },
              emphasis: {
                label: {
                  fontSize: 16
                }
              },
              data: data
            }
          ]
        }

        this.funnelChart.setOption(option)

        // 添加点击事件
        this.funnelChart.on('click', (params) => {
          const data = params.data
          if (data.originalData && data.originalData.id) {
            this.handleGetJumpOrders(data.originalData.id)
          } else {
            // 第一步新客户，跳转到客户页面
            this.handleViewCustomers('all')
          }
        })

        // 添加窗口大小变化事件监听
        window.addEventListener('resize', () => {
          if (this.funnelChart) {
            this.funnelChart.resize()
          }
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.stats-dashboard {
  padding: 10px 0;
}

.stats-section {
  margin-bottom: 25px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 12px 0;
    padding-left: 8px;
  }

  .stats-grid {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px 20px;
  min-width: 180px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  }

  .stat-content {
    flex: 1;

    .stat-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 4px;
      font-weight: 500;
    }

    .stat-number {
      font-size: 28px;
      font-weight: 700;
      line-height: 1;
      margin-bottom: 2px;
    }

    .stat-unit {
      font-size: 12px;
      color: #999;
    }
  }

  .stat-icon {
    margin-left: 16px;

    i {
      font-size: 24px;
      opacity: 0.8;
    }
  }
}

.compact-stats {
  margin-bottom: 20px;

  .compact-stats-row {
    display: flex;
    gap: 20px;
    align-items: center;
  }
}

.compact-stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
  }

  .compact-label {
    font-size: 13px;
    color: #666;
    font-weight: 500;
    white-space: nowrap;
  }

  i {
    font-size: 16px;
  }

  .compact-number {
    font-size: 18px;
    font-weight: 600;
    line-height: 1;
  }
}

// 转化漏斗样式
.funnel-section {
  margin-bottom: 25px;

  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 20px 0;
    padding-left: 8px;
  }
}

.funnel-chart-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0;
  padding: 30px 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.funnel-chart {
  width: 100%;
  height: 600px;
}

// 保持原有样式作为备用
.panel-group {
  margin-top: 18px;
  .card-panel-col{
    margin-bottom: 32px;
  }
  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);
    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }
      .icon-people {
         background: #40c9c6;
      }
      .icon-message {
        background: #36a3f7;
      }
      .icon-money {
        background: #f4516c;
      }
      .icon-shoppingCard {
        background: #34bfa3
      }
    }
    .icon-people {
      color: #40c9c6;
    }
    .icon-message {
      color: #36a3f7;
    }
    .icon-money {
      color: #f4516c;
    }
    .icon-shoppingCard {
      color: #34bfa3
    }
    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }
    .card-panel-icon {
      float: left;
      font-size: 48px;
    }
    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;
      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }
      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}
</style>
